<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Pay_order_return extends CI_Controller {
	public function __construct() {
		parent::__construct();
		$this->load->config("config_pay");
		
	}

	/**
	 * @name get_yeepay_return
	 * @param 定义函数或者方法的参数信息
	 * @return 定义函数或者方法的返回信息
	 * @version 定义版本信息
	 * @description 获取易宝返回数据
	 */
	public function get_yeepay_return() {
		$this->load->helper("yeepay/yeepaycommon");
		$return = getCallBackValue($r0_Cmd,$r1_Code,$p1_MerId,$p2_Order,$p3_Amt,$p4_FrpId,$p5_CardNo,
		$p6_confirmAmount,$p7_realAmount,$p8_cardStatus,$p9_MP,$pb_BalanceAmt,$pc_BalanceAct,$hmac);

		$bRet = CheckHmac($r0_Cmd,$r1_Code,$p1_MerId,$p2_Order,$p3_Amt,$p4_FrpId,$p5_CardNo,$p6_confirmAmount,$p7_realAmount,$p8_cardStatus,
		$p9_MP,$pb_BalanceAmt,$pc_BalanceAct,$hmac);
		if($bRet){
			echo "success";
			$order_sn=$p2_Order;

			$this->load->model('sws_recharge_order_model');
			$trc_order_info	= $this->sws_recharge_order_model->query_order_by_sn($order_sn);

			$this->change_recharge_payment_status($order_sn,$p8_cardStatus);
			$this->change_tran_payment_status($trc_order_info->TRAN_ID,$p8_cardStatus);

			if($r1_Code=="1"){
				$data['pay_time']		=date("Y-m-d H:i:s");
				$data['modified_time']	=date("Y-m-d H:i:s");
				$data['modified_by']	="易宝";
				$order_sn				=$order_sn;
				$data['payment_order']	="无";
				$data['pay_status']		=1;
				$data['payment_fee']	=$p3_Amt;
				$this->load->helper("alipay/alipay_notify");

					
				$this->load->library("pay/pay_transaction");
				$this->sws_recharge_order_model->pay_success($data,$order_sn);

				$this->pay_transaction->pay_tran($trc_order_info->TRAN_ID,$trc_order_info->ACCOUNT_NO,$p3_Amt);
				$this->insert_tran_log($order_sn, $trc_order_info->AMOUNT, 1, $trc_order_info->ACCOUNT_NO,$trc_order_info->MERCHANT_ID,"易宝充值",date("Y-m-d H:i:s"));
			}
		} else{
			$data['error_info']="交易签名无效!";
			$this->load->view("recharge/recharge_error",$data);
			return;
		}
	}



	/**
	 * @name get_alipay_return
	 * @date 2012-10-23
	 * @author eifel
	 * @param 定义函数或者方法的参数信息
	 * @return 定义函数或者方法的返回信息
	 * @version 定义版本信息
	 * @description 获取支付宝返回数据
	 */
	public function get_alipay_return() {

		$this->load->helper("alipay/alipay_notify");
		//↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
		$alipay_config =$this->config->item("alipay_config");
		$partner		= $alipay_config['partner'];					//合作身份者ID，以2088开头的16位纯数字
		$key   			= $alipay_config['key'];	//安全检验码，以数字和字母组成的32位字符
		$seller_email	= $alipay_config['seller_email'];				//签约支付宝账号或卖家支付宝帐户
		//↓↓↓↓↓↓↓↓↓↓以下参数为支付宝默认参数，禁止修改其参数值↓↓↓↓↓↓↓↓↓↓

		$Service_Create				= "alipay.wap.trade.create.direct";
		$Service_authAndExecute		= "alipay.wap.auth.authAndExecute";
		$format						= "xml";
		$sec_id						= "MD5";
		$_input_charset				= "utf-8";
		$v							= "2.0";
		$alipay = new alipay_notify ( $partner, $key, $sec_id, $_input_charset );

		if (!empty($_GET)) {
			$verify_result = $alipay->return_verify ();
			$result =$this->input->get_post("result");
			if ($verify_result&&$result="success") {
				$order_sn=$this->input->get_post("out_trade_no");
				$trc_order_info = $this->get_trade_info($order_sn);
				$this->load->library("encrypt");
				$encrypt_tran_id=$this->encrypt->encode($trc_order_info->TRAN_ID);
				redirect(base_url()."index.php/pay/pay_success?encrypt_tran_id=".$encrypt_tran_id);
			}
			else{
				$data['error_info']="交易签名无效!";
				$this->load->view("recharge/recharge_error",$data);
				return;
			}
		}
	}

	public function get_alipay_notify() {

		$this->load->helper("alipay/alipay_notify");
		//↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
		$alipay_config =$this->config->item("alipay_config");
		$partner		= $alipay_config['partner'];					//合作身份者ID，以2088开头的16位纯数字
		$key   			= $alipay_config['key'];						//安全检验码，以数字和字母组成的32位字符
		$seller_email	= $alipay_config['seller_email'];				//签约支付宝账号或卖家支付宝帐户
		//↓↓↓↓↓↓↓↓↓↓以下参数为支付宝默认参数，禁止修改其参数值↓↓↓↓↓↓↓↓↓↓
		$Service_Create				= "alipay.wap.trade.create.direct";
		$Service_authAndExecute		= "alipay.wap.auth.authAndExecute";
		$format						= "xml";
		$sec_id						= "MD5";
		$_input_charset				= "utf-8";
		$v							= "2.0";
		$alipay = new alipay_notify ( $partner, $key, $sec_id, $_input_charset );
		if (!empty($_POST)) {
			$verify_result = $alipay->notify_verify();
			if ($verify_result) {
				$status = getDataForXML ( $_POST ['notify_data'], '/notify/trade_status' ); // 返回token
				if ($status == 'TRADE_FINISHED') {
					echo "success";
					$order_sn 		= getDataForXML ( $_POST ['notify_data'], '/notify/out_trade_no' );
					$payment_sn 	= getDataForXML ( $_POST ['notify_data'], '/notify/trade_no' );
					$payment_fee 	= getDataForXML ( $_POST ['notify_data'], '/notify/total_fee' );
					$this->change_recharge_status($order_sn,$payment_sn,$payment_fee);
				} else {
					echo "fail"; // 交易未完成
				}
			} else {
				echo "fail";
			}
		}
	}

	public function get_tenpay_return() {
		$this->load->helper("tenpay/ResponseHandler.class.php");
		$this->load->helper("tenpay/RequestHandler.class.php");
		$this->load->helper("tenpay/client/ClientResponseHandler.class.php");
		$this->load->helper("tenpay/client/TenpayHttpClient.class.php");

		$tenpay_config =$this->config->item("tenpay");
		$partner	= $tenpay_config['partner'];
		$key 		= $tenpay_config['key'];

		/* 创建支付应答对象 */
		$resHandler = new ResponseHandler();
		$resHandler->setKey($key);

		//判断签名
		if($resHandler->isTenpaySign()) {

			//通知id
			$notify_id = $resHandler->getParameter("notify_id");

			//通过通知ID查询，确保通知来至财付通
			//创建查询请求
			$queryReq = new RequestHandler();
			$queryReq->init();
			$queryReq->setKey($key);
			$queryReq->setGateUrl("https://gw.tenpay.com/gateway/verifynotifyid.xml");
			$queryReq->setParameter("partner", $partner);
			$queryReq->setParameter("notify_id", $notify_id);

			//通信对象
			$httpClient = new TenpayHttpClient();
			$httpClient->setTimeOut(5);
			//设置请求内容
			$httpClient->setReqContent($queryReq->getRequestURL());

			//后台调用
			if($httpClient->call()) {
				//设置结果参数
				$queryRes = new ClientResponseHandler();
				$queryRes->setContent($httpClient->getResContent());
				$queryRes->setKey($key);

				//判断签名及结果
				//只有签名正确,retcode为0，trade_state为0才是支付成功
				if($queryRes->isTenpaySign() && $queryRes->getParameter("retcode") == "0" && $queryRes->getParameter("trade_state") == "0" && $queryRes->getParameter("trade_mode") == "1" ) {
					//取结果参数做业务处理
					$out_trade_no = $queryRes->getParameter("out_trade_no");
					//财付通订单号
					$transaction_id = $queryRes->getParameter("transaction_id");
					//金额,以分为单位
					$total_fee = $queryRes->getParameter("total_fee");
					//如果有使用折扣券，discount有值，total_fee+discount=原请求的total_fee
					$discount = $queryRes->getParameter("discount");



					$trc_order_info = $this->get_trade_info($out_trade_no);
					$this->load->library("encrypt");
					$encrypt_tran_id=$this->encrypt->encode($trc_order_info->TRAN_ID);
					redirect(base_url()."index.php/pay/pay_success?encrypt_tran_id=".$encrypt_tran_id);



				} else {

					log_message("error","验证签名失败 或 业务错误信息:trade_state=" . $queryRes->getParameter("trade_state") . ",retcode=" . $queryRes->getParameter("retcode"). ",retmsg=" . $queryRes->getParameter("retmsg"));
					$data['error_info']="支付失败，交易签名无效!";
					$this->load->view("recharge/recharge_error",$data);
					return;

				}

				//获取查询的debug信息,建议把请求、应答内容、debug信息，通信返回码写入日志，方便定位问题
				/*
				 echo "<br>------------------------------------------------------<br>";
				 echo "http res:" . $httpClient->getResponseCode() . "," . $httpClient->getErrInfo() . "<br>";
				 echo "query req:" . htmlentities($queryReq->getRequestURL(), ENT_NOQUOTES, "GB2312") . "<br><br>";
				 echo "query res:" . htmlentities($queryRes->getContent(), ENT_NOQUOTES, "GB2312") . "<br><br>";
				 echo "query reqdebug:" . $queryReq->getDebugInfo() . "<br><br>" ;
				 echo "query resdebug:" . $queryRes->getDebugInfo() . "<br><br>";
				 */
			}else {
				//通信失败
				//echo "fail";
				//后台调用通信失败,写日志，方便定位问题，这些信息注意保密，最好不要打印给用户
				log_message("error","订单通知查询失败:" . $httpClient->getResponseCode() ."," . $httpClient->getErrInfo());
			}
		} else {
			//签名错误
			log_message("error","订单通知查询失败");
			$data['error_info']="支付失败!";
			$this->load->view("recharge/recharge_error",$data);
			return;
		}

	}


	public function get_tenpay_notify() {
		$this->load->helper("tenpay/ResponseHandler.class.php");
		$this->load->helper("tenpay/RequestHandler.class.php");
		$this->load->helper("tenpay/client/ClientResponseHandler.class.php");
		$this->load->helper("tenpay/client/TenpayHttpClient.class.php");

		$tenpay_config =$this->config->item("tenpay");
		$partner	= $tenpay_config['partner'];
		$key 		= $tenpay_config['key'];

		/* 创建支付应答对象 */
		$resHandler = new ResponseHandler();
		$resHandler->setKey($key);

		if($resHandler->isTenpaySign()) {

			//通知id
			$notify_id = $resHandler->getParameter("notify_id");

			//通过通知ID查询，确保通知来至财付通
			//创建查询请求
			$queryReq = new RequestHandler();
			$queryReq->init();
			$queryReq->setKey($key);
			$queryReq->setGateUrl("https://gw.tenpay.com/gateway/verifynotifyid.xml");
			$queryReq->setParameter("partner", $partner);
			$queryReq->setParameter("notify_id", $notify_id);

			//通信对象
			$httpClient = new TenpayHttpClient();
			$httpClient->setTimeOut(5);
			//设置请求内容
			$httpClient->setReqContent($queryReq->getRequestURL());

			//后台调用
			if($httpClient->call()) {
				//设置结果参数
				$queryRes = new ClientResponseHandler();
				$queryRes->setContent($httpClient->getResContent());
				$queryRes->setKey($key);

				//判断签名及结果
				//只有签名正确,retcode为0，trade_state为0才是支付成功
				if($queryRes->isTenpaySign() && $queryRes->getParameter("retcode") == "0" && $queryRes->getParameter("trade_state") == "0" && $queryRes->getParameter("trade_mode") == "1" ) {
					//取结果参数做业务处理
					$out_trade_no = $queryRes->getParameter("out_trade_no");
					//财付通订单号
					$transaction_id = $queryRes->getParameter("transaction_id");
					//金额,以分为单位
					$total_fee = $queryRes->getParameter("total_fee");
					//如果有使用折扣券，discount有值，total_fee+discount=原请求的total_fee
					$discount = $queryRes->getParameter("discount");

					//------------------------------
					//处理业务开始
					//------------------------------
					$this->change_recharge_status($out_trade_no,$transaction_id,($total_fee+$discount)/100);
					//处理数据库逻辑
					//注意交易单不要重复处理
					//注意判断返回金额

					//------------------------------
					//处理业务完毕
					//------------------------------
					echo "success";

				} else {
					//错误时，返回结果可能没有签名，写日志trade_state、retcode、retmsg看失败详情。
					//echo "验证签名失败 或 业务错误信息:trade_state=" . $queryRes->getParameter("trade_state") . ",retcode=" . $queryRes->getParameter("retcode"). ",retmsg=" . $queryRes->getParameter("retmsg") . "<br/>" ;
					echo "fail";
				}

				//获取查询的debug信息,建议把请求、应答内容、debug信息，通信返回码写入日志，方便定位问题
				/*
				 echo "<br>------------------------------------------------------<br>";
				 echo "http res:" . $httpClient->getResponseCode() . "," . $httpClient->getErrInfo() . "<br>";
				 echo "query req:" . htmlentities($queryReq->getRequestURL(), ENT_NOQUOTES, "GB2312") . "<br><br>";
				 echo "query res:" . htmlentities($queryRes->getContent(), ENT_NOQUOTES, "GB2312") . "<br><br>";
				 echo "query reqdebug:" . $queryReq->getDebugInfo() . "<br><br>" ;
				 echo "query resdebug:" . $queryRes->getDebugInfo() . "<br><br>";
				 */
			}else {
				//通信失败
				echo "fail";
				//后台调用通信失败,写日志，方便定位问题
				//echo "<br>call err:" . $httpClient->getResponseCode() ."," . $httpClient->getErrInfo() . "<br>";
			}


		} else {
			//回调签名错误
			echo "fail";
			//echo "<br>签名失败<br>";
		}

	}


	public function get_upmp_return(){
		$status =$this->input->get_post("status");
		if ($status=="success") {
			$tn=$this->input->get_post("tn");
			$this->load->model("sws_recharge_order_model");
			$trc_order_info = $this->sws_recharge_order_model->query_order_by_payment_order($tn);
			if ($trc_order_info==null){
				$data['error_info']="您支付的订单不存在!";
				$this->load->view("recharge/recharge_error",$data);
				return;
					
			}
			$this->load->library("encrypt");
			$encrypt_tran_id=$this->encrypt->encode($trc_order_info['TRAN_ID']);
			redirect(base_url()."index.php/pay/pay_success?encrypt_tran_id=".$encrypt_tran_id);
		}
		elseif ($status=="fail"){
			$data['error_info']="支付失败!";
			$this->load->view("recharge/recharge_error",$data);
			return;

		}elseif ($status=="cancel"){
			$data['error_info']="你已经取消了这次交易!";
			$this->load->view("recharge/recharge_error",$data);
			return;

		}


	}

	public function get_upmp_notify() {
		$this->load->helper("upmp/upmp_service");

		if (UpmpService::verifySignature($_POST)){// 服务器签名验证成功
			//请在这里加上商户的业务逻辑程序代码
			//获取通知返回参数，可参考接口文档中通知参数列表(以下仅供参考)
			$transStatus = $_POST['transStatus'];// 交易状态
			if (""!=$transStatus && "00"==$transStatus){
				$out_trade_no 	=  $_POST['orderNumber'];
				$transaction_id =  $_POST['qn'];
				$total_fee 		=  ($_POST['settleAmount']/100);
				//------------------------------
				//处理业务开始
				//------------------------------
				$this->change_recharge_status($out_trade_no,$transaction_id,$total_fee);
					
				echo "success";

			}else {
			}
		}else {// 服务器签名验证失败
			echo "fail";
		}
	}

	public function query_upmp_order_status() {
		$out_trade_no = $this->input->get_post("out_trade_no");
		$order_info		=$this->get_trade_info($out_trade_no);
		$upmp['out_trade_no'] 	= $out_trade_no;
		$upmp['orderTime']		= $order_info->CREATED_TIME;
		$this->load->library("pay/upmp");
		$return = $this->upmp->query($upmp);

	}
	/**
	 * @access private
	 * @author hyman
	 * @param varchar $order_sn,int $order_sn
	 * @return null
	 * @description:change recharge payment status.
	 * */
	private function change_recharge_payment_status($order_sn,$payment_status) {
		$this->load->model("sws_recharge_order_model");
		$this->sws_recharge_order_model->change_recharge_payment_status($order_sn,$payment_status);
	}

	/**
	 * @access private
	 * @author hyman
	 * @param int $tran_id,int $payment_status
	 * @return null
	 * @description:change payment status.
	 * */
	private function change_tran_payment_status($tran_id,$payment_status) {
		$this->load->model("sws_recharge_order_model");
		$this->sws_recharge_order_model->change_tran_payment_status($tran_id,$payment_status);
	}

	/**
	 * @access private
	 * @author hyman
	 * @param varchar $order_sn
	 * @return mixed $trade_info
	 * @description:get trade infos by using order_sn
	 * */
	private function get_trade_info($order_sn) {
		$this->load->model("sws_recharge_order_model");
		return $this->sws_recharge_order_model->query_order_by_sn($order_sn);
	}

	private   function change_recharge_status($order_sn,$payment_order,$payment_fee) {
		$data['pay_time']	=date("Y-m-d H:i:s");
		$data['modified_time']	=date("Y-m-d H:i:s");
		$data['modified_by']	="第三方通知";
		$order_sn		=$order_sn;
		$data['payment_order']	=$payment_order;
		$data['pay_status']	=1;
		$data['payment_fee']	=$payment_fee;
		$this->load->helper("alipay/alipay_notify");
		$this->load->model("sws_recharge_order_model");
		$this->sws_recharge_order_model->pay_success($data,$order_sn);
		$trc_order_info	= $this->get_trade_info($order_sn);
		$this->load->library("pay/pay_transaction");
		$this->pay_transaction->pay_tran($trc_order_info->TRAN_ID,$trc_order_info->ACCOUNT_NO,$payment_fee);
		$this->change_tran_payment_status($trc_order_info->TRAN_ID,"0");
		$this->insert_tran_log($order_sn, $trc_order_info->AMOUNT, 1, $trc_order_info->ACCOUNT_NO,$trc_order_info->MERCHANT_ID,"支付宝充值",date("Y-m-d H:i:s"));
	}

	/**
	 * @access private
	 * @author hyman
	 * @param $transaction_code,$amount,$transaction_type,$account_no,$merchant_id,$product_name,$transaction_time
	 * @return null
	 * @description: log...
	 * */
	private function insert_tran_log($transaction_code,$amount,$transaction_type,$account_no,$merchant_id,$product_name,$transaction_time) {
		$log_info['transaction_code']=$transaction_code;
		$log_info['amount']=$amount;
		$log_info['transaction_type']=$transaction_type;
		$log_info['account_no']=$account_no;
		$log_info['merchant_id']=$merchant_id;
		$log_info['product_name']=$product_name;
		$log_info['transaction_time']=$transaction_time;
		$this->load->model("sws_transaction_log_model");
		$this->sws_transaction_log_model->insert_log($log_info);
	}



}
